<?php

namespace App\Services;

use Illuminate\Support\Facades\Cache;
use Exception;

class Qcloud
{
    protected $secretId = '';
    protected $secretKey = '';
    protected $region = '';
    protected $bucket = '';
    protected $cosClient;

    public $url = '';

    public function __construct()
    {
        $setting = Config::getUploadSetting();
        $config = $setting['tencentyun'] ?? [];

        // 用于签名的公钥和私钥
        $this->secretId = $config['secret_id'];
        $this->secretKey = $config['secret_key'];
        $this->region = $config['region'];
        $this->bucket = $config['bucket'];
        $this->url = $config['url'];

        // 初始化签权对象
        $this->cosClient = new \Qcloud\Cos\Client(
            [
                'region' => $this->region,
                'schema' => 'https', //协议头部，默认为http
                'credentials' => [
                    'secretId' => $this->secretId,
                    'secretKey' => $this->secretKey,
                    //'token' => $tmpToken // 使用临时密钥需要填入
                ]
            ]
        );
    }

    /**
     * 上传文件
     */
    public function uploadFile($tmpFile)
    {
        try {
            $cosClient = $this->cosClient;
            $bucket = $this->bucket;
            $file = fopen($tmpFile['tmp_name'], 'rb');
            if ($file) {
                $extStr = explode('.', $tmpFile['name']);
                // 重命名
                //$name = get_UUID() . '.' . $extStr[count($extStr) - 1];
                $name = date('Y-m') . '/' . date('d') . '/' . date('His') . '_' . mt_rand(10000, 99999);
                $name .= '.' . $extStr[count($extStr) - 1];
                $result = $cosClient->Upload($bucket, $name, $file);
                //@fclose($file);

                return ['code' => '1', 'msg' => '上传成功', 'key' => $name, 'result' => $result];
            } else {
                return ['code' => '0', 'msg' => 'error', 'key' => ''];
            }
        } catch (Exception $e) {
            return ['code' => '0', 'msg' => $e->getMessage(), 'key' => ''];
        }
    }

    /**
     * 删除文件
     */
    public function delFile($key)
    {
        return true;
    }
}
